import { useEffect } from "react";
import { useMutation } from "@apollo/react-hooks";
import gql from "graphql-tag";
import { notification } from "antd";

import { QUERY } from "../hooks/useTable";
import { usePageContext } from "./useContext";
import { handleErrors } from "../../../utils/handleErrors";
import { useForm } from "./useForm";
import { SYS_AUTHORITIES } from "../../SysRole/hooks/useAuthorities";

const UPDATE = gql`
  mutation UpdateSysAuthority($authority: UpdateSysAuthorityInput!) {
    updateSysAuthority(authority: $authority) {
      id
    }
  }
`;

export const useUpdate = ({ form }) => {
  const { handleClose } = useForm();
  const {
    state: {
      form: { current, isEdit }
    },
    dispatch
  } = usePageContext();

  const [updateSysAuthority] = useMutation(UPDATE, {
    onCompleted: ({ updateSysAuthority }) => {
      if (updateSysAuthority) {
        notification.success({ message: "更新权限成功！" });
        handleClose();
      }
    },
    onError: ({ graphQLErrors, networkError }) => {
      handleErrors({ graphQLErrors, networkError, form });
    },
    refetchQueries: [
      {
        query: QUERY
      },
      { query: SYS_AUTHORITIES }
    ]
  });

  const handleSubmit = e => {
    e.preventDefault();
    form.validateFields((err, values) => {
      if (!err) {
        let { name, type, path, parentId, ...data } = values;
        path = type === "MENU" ? `${current.path || ""}/${path}` : null;
        updateSysAuthority({
          variables: {
            authority: { ...data, path, id: current.id }
          }
        });
      }
    });
  };

  useEffect(() => {
    const setForm = ({ name, description, type, path, isSystem, parent }) => {
      let spt = `${(current.parent && current.parent.name) || "AUTH"}_`;
      form.setFieldsValue({
        name: name.split(spt).pop(),
        description,
        type,
        path: path && path.split("/").pop(),
        isSystem,
        parentId: parent && parent.id
      });
    };

    if (isEdit) {
      if (current) {
        setForm({ ...current });
        dispatch({ type: "SET_FORM", payload: { handleSubmit } });
        dispatch({ type: "TOGGLE_MODAL", payload: true });
      } else {
        form.resetFields();
        dispatch({ type: "TOGGLE_MODAL", payload: false });
      }
    }
  }, [current, isEdit]);
};
